//
//  InfoViewController.m
//  VideoDiaryClass
//
//  Created by Wang Haitao on 15/10/20.
//  Copyright © 2015年 qianfeng. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "InfoViewController.h"
#import "UIViewAdditions.h"
#import "Masonry.h"
#import "DiaryFile.h"

@interface InfoViewController () <UIScrollViewDelegate>
{
    IBOutlet UIButton * colorButton0;
    IBOutlet UIButton * colorButton1;
    IBOutlet UIButton * colorButton2;
    IBOutlet UIButton * colorButton3;
    IBOutlet UIButton * colorButton4;
    IBOutlet UIButton * colorButton5;
    IBOutlet UIButton * colorButton6;
    IBOutlet UIButton * colorButton7;
    IBOutlet UIButton * colorButton8;
    IBOutlet UIButton * colorButton9;
}

@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewBottomConstraint;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (nonatomic) NSArray * previewButtonArray;
@property (nonatomic) NSArray * colorButtonArray;

@property (nonatomic) NSInteger selectedImageIndex;

@end

@implementation InfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:9];
    for (NSInteger i=1; i<=9; i++) {
        UIButton * button = (UIButton *)[self.scrollView viewWithTag:i];
        [array addObject:button];
        [button addTarget:self action:@selector(imageButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"videoselect"]];
        [button addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(button.mas_centerX);
            make.centerY.equalTo(button.mas_centerY);
        }];
        imageView.tag = 10;
        imageView.hidden = YES;
    }
    
    _selectedImageIndex = -1;
    
    self.previewButtonArray = array;
    
    self.colorButtonArray = [NSArray arrayWithObjects:colorButton0, colorButton1, colorButton2, colorButton3, colorButton4, colorButton5, colorButton6, colorButton7, colorButton8, colorButton9, nil];
    
    
    self.scrollView.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    [self performSelector:@selector(grabImage) withObject:nil afterDelay:0.5];
}

- (void) grabImage
{
    AVAsset * asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:self.diary.videoPath]];
    
    AVAssetImageGenerator * imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    NSMutableArray * timeArray = [NSMutableArray arrayWithCapacity:9];
    
    self.diary.duration = CMTimeGetSeconds(asset.duration);
    
    for (NSInteger i=0; i<9; i++) {
        NSValue * value = [NSValue valueWithCMTime:CMTimeMakeWithSeconds(i * self.diary.duration/9, asset.duration.timescale)];
        [timeArray addObject:value];
    }
    
    [imageGenerator generateCGImagesAsynchronouslyForTimes:timeArray completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        
        if (result!=AVAssetImageGeneratorSucceeded) {
            return;
        }
        
        for (NSInteger i=0; i<timeArray.count; i++) {
            NSValue * value = timeArray[i];
            CMTime requested = [value CMTimeValue];
            
            if (CMTimeCompare(requested, requestedTime)==0) {
                UIImage * requestedImage = [UIImage imageWithCGImage:image];
                UIButton * button = self.previewButtonArray[i];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [button setBackgroundImage:requestedImage forState:UIControlStateNormal];
                    if (self.selectedImageIndex==-1) {
                        self.selectedImageIndex = i;
                    }

                });
                break;
            }
        }
        
    }];
    
}

- (void) keyboardWillShow: (NSNotification *) notify
{
    [self updateKeyboardStatus:notify show:YES];
}

- (void) keyboardWillHide: (NSNotification *) notify
{
    [self updateKeyboardStatus:notify show:NO];
}

- (void) updateKeyboardStatus: (NSNotification * )notify show: (BOOL)isShow
{
    NSDictionary *userInfo = [notify userInfo];
    
    NSTimeInterval animationDuration;
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    
    CGRect kbFrame;
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&kbFrame];
    
    self.scrollViewBottomConstraint.constant = isShow ? CGRectGetHeight(kbFrame) : 0;
    
    [UIView animateWithDuration:animationDuration
                     animations:^{
                         [self.view layoutIfNeeded];
                     }
                     completion:^(BOOL finished) {
                         [self.scrollView scrollRectToVisible: CGRectOffset(self.textView.frame, 0, 10) animated:YES];
                         
                     }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView==self.scrollView) {
        [self.textView resignFirstResponder];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void) imageButtonClicked: (UIButton *)button
{
    NSInteger index = [self.previewButtonArray indexOfObject:button];
    self.selectedImageIndex = index;
}

- (void)setSelectedImageIndex:(NSInteger)selectedImageIndex
{
    if (selectedImageIndex<0) {
        return;
    }
    
    if (selectedImageIndex==_selectedImageIndex) {
        return;
    }
    
    UIButton * nextButton = self.previewButtonArray[selectedImageIndex];
    UIImage *image = [nextButton backgroundImageForState:UIControlStateNormal];
    if (!image) {
        return;
    }
    
    if (_selectedImageIndex >= 0) {
        UIButton * lastButton = self.previewButtonArray[_selectedImageIndex];
        UIImageView * imageView = (UIImageView *)[lastButton viewWithTag:10];
        imageView.hidden = YES;
    }
    
    _selectedImageIndex = selectedImageIndex;
    
    UIButton * currentButton = self.previewButtonArray[_selectedImageIndex];
    UIImageView * imageView = (UIImageView *)[currentButton viewWithTag:10];
    imageView.hidden = NO;
}

- (IBAction) colorButtonClicked: (UIButton *)colorButton
{
    NSString * title = [colorButton titleForState:UIControlStateNormal];
    
    if ([title isEqualToString:@"X"]) {
        return;
    }
    
    for (UIButton * button in self.colorButtonArray) {
        [button setTitle:@"" forState:UIControlStateNormal];
    }
    
    [colorButton setTitle:@"X" forState:UIControlStateNormal];
}

- (IBAction)saveAndQuit:(id)sender
{
    UIImage * image;
    if (self.selectedImageIndex<0) {
        image = [UIImage imageNamed:@"previewPlaceholder"];
    }
    else {
        UIButton * button = self.previewButtonArray[self.selectedImageIndex];
        image = [button backgroundImageForState:UIControlStateNormal];
    }
    
    NSData * data = UIImagePNGRepresentation(image);
    [data writeToFile:self.diary.imagePath atomically:NO];
    
    for (UIButton * button in self.colorButtonArray) {
        NSString * title = [button titleForState:UIControlStateNormal];
        if ([title isEqualToString:@"X"]) {
            self.diary.color = button.backgroundColor;
            break;
        }
    }
    
    self.diary.content = self.textView.text;
    
    [[DiaryFile sharedInstance] addDiary:self.diary];
    [self performSegueWithIdentifier:@"BackToMain" sender:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
